const { ipcRenderer } = require('electron')

let isMenuVisible = false
const bubbleMenu = document.getElementById('bubbleMenu')
const mainBubble = document.getElementById('mainBubble')
const bubbleContent = mainBubble.querySelector('.bubble-content')
const toggleNotesBtn = document.getElementById('toggleNotes')
const addNoteBtn = document.getElementById('addNote')
const settingsBtn = document.getElementById('settings')

// 创建提示元素
const tooltip = document.createElement('div')
tooltip.className = 'tooltip'
tooltip.style.display = 'none'
document.body.appendChild(tooltip)

// 显示提示
function showTooltip(message, button) {
    const rect = button.getBoundingClientRect()
    tooltip.textContent = message
    tooltip.style.display = 'block'
    tooltip.style.left = rect.left + 'px'
    tooltip.style.top = (rect.top - tooltip.offsetHeight - 5) + 'px'

    // 3秒后自动隐藏
    setTimeout(() => {
        tooltip.style.display = 'none'
    }, 3000)
}

// 切换菜单显示状态
function toggleMenu() {
    isMenuVisible = !isMenuVisible
    bubbleMenu.style.display = isMenuVisible ? 'block' : 'none'
}

// 右键点击显示/隐藏菜单
bubbleContent.addEventListener('contextmenu', (e) => {
    e.preventDefault()
    e.stopPropagation()
    toggleMenu()
})

// 左键点击和拖动
let isDragging = false
let startPos = { x: 0, y: 0 }

bubbleContent.addEventListener('mousedown', (e) => {
    if (e.button === 0) { // 左键
        e.preventDefault()
        isDragging = true
        startPos = { x: e.clientX, y: e.clientY }
        
        // 通知主进程开始拖动
        ipcRenderer.send('start-drag-mode')
    }
})

document.addEventListener('mousemove', (e) => {
    if (isDragging) {
        // 发送新位置给主进程
        ipcRenderer.send('update-bubble-position', {
            x: e.screenX,
            y: e.screenY
        })
    }
})

document.addEventListener('mouseup', () => {
    if (isDragging) {
        isDragging = false
        // 通知主进程结束拖动
        ipcRenderer.send('end-drag-mode')
    }
})

// 添加便签
addNoteBtn.addEventListener('click', () => {
    ipcRenderer.send('add-note')
})

// 显示/隐藏所有便签
let notesVisible = true
toggleNotesBtn.addEventListener('click', () => {
    ipcRenderer.send('toggle-notes-visibility')
})

// 监听没有便签的提示
ipcRenderer.on('no-notes-to-toggle', () => {
    showTooltip('没有可以隐藏的便签', toggleNotesBtn)
})

// 打开设置窗口
settingsBtn.addEventListener('click', () => {
    ipcRenderer.send('open-settings')
})

// 点击其他地方关闭菜单
document.addEventListener('click', (e) => {
    if (isMenuVisible && !e.target.closest('.bubble-container')) {
        toggleMenu()
    }
}) 